/**
 * Created by jiexin on 2017/9/15.
 */
layui.use(['form', 'element', 'layer', 'table', 'laytpl'], function() {
    var form = layui.form;
    var element = layui.element;
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer;
    var laytpl = layui.laytpl;

    //table 表格长宽设置
    var hostleftall = document.getElementById("hosts_left");
    var hostleftw = hostleftall.offsetWidth-60;
    var hostlefth = hostleftall.offsetHeight - 290;

    var hostrightall = document.getElementById("hosts_right");
    var hostrightw = hostrightall.offsetWidth;
    var hostrighth = hostrightall.offsetHeight - 160;
    var getdivh = hostrightall.offsetHeight - 100;

    //添加修改按钮出事状态：1添加、2修改
    var buttom_status = 1;

    //
    var keys_json = {};
    for (var i=0; i < keys_list.length; i++) {
        $("#keyslist").append('<option value="'+ i + '">' + keys_list[i] + '</option>');
        keys_json[keys_list[i]] = i
    }
    form.render('select');

    //
    var table_format_host = [[
        {checkbox:true}
         , {field: 'host_id', align: 'center', title: 'ID', width: "10%"}
         , {field: 'host_ip', align: 'center', title: 'IP地址', width: "28%"}
         , {field: 'host_describ', title: '描述', width: "28%"}
         , {field: 'host_user', title: '用户', width: "15%"}
         , {field: 'host_port', title: '端口', width: "15%"}
         , {fixed: 'right',width: "15%", align: 'center',  title: '操作', toolbar: '#hostsDemo'}
    ]];

    $('.layui-table-host').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        //var tableid = document.getElementById('update').id;
        console.log(tableid);
        createtable(etaleid,tableid,host_list,table_format_host, hostrighth);
        hosttool(toolid,tableid);
    });

    //
    var table_format_group = [[
         // {field: 'group_id', align: 'center', title: 'ID', width: "10%"}
         {field: 'group_name', align: 'center', title: '组名', width: "20%"}
         , {field: 'group_key', align: 'center', title: 'Key名称', width: "20%"}
         , {field: 'group_describ', title: '描述', width: "20%"}
         , {field: 'group_using', title: '状态', width: "18%",  templet: '#groupstatus'}
         , {fixed: 'right',width: "30%", align: 'center',  title: '操作', toolbar: '#groupbutton', templet: '#groupbutton'}
    ]];

    //
    $('.layui-table-group').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        //var tableid = document.getElementById('update').id;
        console.log(tableid);
        createtableg(etaleid,tableid,group_list,table_format_group, hostlefth);
        grouptool(toolid,tableid);
    });

    var get_list_data = [];
    var get_txt_data = "";
    var hosttable;
    function createtable(etaleid,tableid,datas,table_format,table_height) {
        hosttable = table.render({
            elem: etaleid,
            id: tableid,
            //url: '/demo/table/user/',
            width: hostrightw,
            height: table_height,
            limit: 1000,
            data: datas,
            cols: table_format
        });
        active = {
            getCheckLength: function () {
                var checkStatus = table.checkStatus(tableid);
                var data = checkStatus.data;
                layer.msg('添加了：' + data.length + ' 个');
                get_txt_data = "";
                get_list_data = [];
                for (var i=0; i<data.length; i++) {
                    // if ($.inArray(data[i]["host_ip"], get_list_data) === -1) {
                    get_list_data.push(data[i]["host_ip"]);
                    if (get_txt_data === ""){
                        get_txt_data = get_txt_data + data[i]["host_ip"] ;
                    }else{
                        get_txt_data = get_txt_data + "," + data[i]["host_ip"]
                    }
                    // }else(console.log("存在"));
                }
                $("#groupip").val(get_txt_data)
            }
        }
    }


    function hosttool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'delhost') {
               $.ajax({
                    url: "/yaml-del/",
                    dataType: 'json',
                    type: 'POST',
                    data: {"id": data["host_id"], "type": "host"},
                    success: function (statusdata) {
                        hosttable.reload({
                             data: statusdata["data_list"]
                        });
                    }
               })
            }
        });
    }

    var grouptable;
    function createtableg(etaleid,tableid,datas,table_format,table_height) {
        grouptable = table.render({
            elem: etaleid,
            id: tableid,
            //url: '/demo/table/user/',
            // width: 440,
            height: table_height,
            limit: 1000,
            data: datas,
            cols: table_format
        });
    }

    $("#getlistdiv").css({"top": - getdivh+'px',"left": 310 +'px'});

    var modifydata;
    function grouptool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'checkgroup') {
                layer.msg(
                    content=iplist(tr.index()),
                    {
                    time: 200000,
                    //200s后自动关闭
                    btn: ['确定'],
                    success: function (layero) {
                        var btn = layero.find('.layui-layer-btn');
                        btn.css('text-align', 'center');
                    }
                });
            }else if (layEvent === 'modifygroup') {
                if (data["group_using"] === 0){
                    modifydata = group_list[tr.index()];
                    $("#groupname").val(group_list[tr.index()]["group_name"]);
                    $("#groupdescribe").val(group_list[tr.index()]["group_describ"]);
                    $("#keyslist").val(keys_json[group_list[tr.index()]["group_key"]]);
                    $("#groupip").val(iptext(group_list[tr.index()]["group_host"]));
                    form.render("select");
                    buttom_status = 2
                }else{
                    layer.msg("禁用状态，不允许修改！")
                }
            }else if (layEvent === 'disgroup') {
                dissend(tr,1)
            }else if (layEvent === 'engroup') {
                dissend(tr,0)
            }else if (layEvent === 'delgroup') {
                $.ajax({
                    url: "/yaml-del/",
                    dataType: 'json',
                    type: 'POST',
                    data: {"id": data["group_id"], "type": "group"},
                    success: function (statusdata) {
                        grouptable.reload({
                             data: statusdata["data_list"]
                        });
                    }
               })
            }
        });
    }

    function iptext(ipdata) {
        var ip_text="";
        var ip_list = [];
        console.log(ipdata.length);
        for (var i=0; i<ipdata.length; i++) {
            if (ipdata.length > 1){
                if (i === ipdata.length -1){
                    ip_text = ip_text + ipdata[i]["host_ip"];
                }else{
                    ip_text = ip_text + ipdata[i]["host_ip"] + ',';
                }

            }else{
                ip_text = ip_text + ipdata[i]["host_ip"];
            }
            ip_list.push(ipdata[i]["host_ip"])
        }
        get_list_data = ip_list;
        get_txt_data = ip_text;
        return ip_text
    }

    function iplist(groupindex) {
        var ip_list = group_list[groupindex]["group_host"];
        var contxt = '<div style="padding: 50px; line-height: 22px; font-weight: 300; text-align:center">';
        for (var i=0; i<=ip_list.length; i++) {
            if (i === ip_list.length) {
                contxt = contxt + '</div>'
            } else {
                if (ip_list.length > 1){
                    if ( i  === ip_list.length - 1){
                        contxt = contxt + ip_list[i]["host_ip"]
                    }else{
                        contxt = contxt + ip_list[i]["host_ip"] + ','
                    }
                }else{
                    contxt = contxt + ip_list[i]["host_ip"]
                }

            }
        }
        return contxt
    }

    function dissend(sendtr,sendstatus) {
        $.ajax({
            url: '/yaml-dis/',
            dataType: 'json',
            type: 'POST',
            data: {"id": group_list[sendtr.index()]["group_id"], "status":sendstatus, "type": "group"},
            success: function (statusdata) {
                if (statusdata["status"] === 0) {
                    if (sendstatus === 0){
                        sendtr.find("td").find(".laytable-cell-2-group_using").html('<span class="label label-success">已启用</span>');
                        sendtr.find("td").find(".laytable-cell-2-5").find(".handle-btn-start").replaceWith('<span title="停用" class="handle-btn handle-btn-stop"  lay-event="disgroup"><i class="layui-icon">&#xe651;</i></span>');
                        group_list[sendtr.index()]["group_using"] = sendstatus;
                        layer.msg("启用成功！")
                    } else {
                        sendtr.find("td").find(".laytable-cell-2-group_using").html('<span class="label label-default">已禁用</span>');
                        sendtr.find("td").find(".laytable-cell-2-5").find(".handle-btn-stop").replaceWith('<span title="启用" class="handle-btn  handle-btn-start" lay-event="engroup"><i class="layui-icon">&#xe652;</i></span>');
                        group_list[sendtr.index()]["group_using"] = sendstatus;
                        layer.msg("禁用成功！")
                    }
                } else {
                    layer.msg("状态修改失败")
                }
            }
        })
    }

    //
    form.on('submit(submithostip)', function(data){
        console.log(data.field);
        var hostdata = data.field;
        $.ajax({
            url: '/yaml-add-host/',
            dataType: 'json',
            type: 'POST',
            data: {"data": JSON.stringify(hostdata)},
            success: function (statusdata) {
                host_list = statusdata["host_list"];
                var host_status = statusdata["status"];
                if (host_status === 0 ) {
                    hosttable.reload({
                        data: host_list
                    });
                    $('#resethostip').trigger("click");
                    layer.msg('添加成功！')
                }else {
                    layer.msg('ip重复！')
                }
            }
        })
    });

    //
    form.on('submit(submitgroup)', function(data){
        var groupdata = data.field;
        if (buttom_status === 2){
            layer.msg("当前为修改状态！")
        }else{
            get_list_data = [];
            get_txt_data = "";
            groupdata["keyslist"] = keys_list[groupdata["keyslist"]];
            $.ajax({
                url: '/yaml-add-group/',
                dataType: 'json',
                type: 'POST',
                data: {"data": JSON.stringify(groupdata)},
                success: function (statusdata) {
                    group_list = statusdata["group_list"];
                    console.log(group_list);
                    var group_status = statusdata["status"];
                    if (group_status === 0){
                        grouptable.reload({
                            data: group_list
                        });
                        $('#resetgroup').trigger("click");
                        layer.msg('添加成功！')
                    }else if (group_status === 1){
                        layer.msg('组名重复！')
                    }else{
                        layer.msg('执行异常！')
                    }
                }
            })
        }

    });

    //
    form.on('submit(modgroup)', function(data){
        if (buttom_status === 1) {
            layer.msg("非修改状态")
        }else{
            var groupdata = data.field;
            var modifygroup = {};
            var list_json = {"groupname":"group_name", "groupip":"group_host", "keyslist":"group_key", "groupdescribe":"group_describ"};
            groupdata["keyslist"] = keys_list[groupdata["keyslist"]];
            $.each(groupdata, function (k,v) {
                if (k === "groupip"){
                    var old_ip_list = modifydata["group_host"];
                    var old_ip_txt = "";
                    for (var i=0; i<old_ip_list.length; i++) {
                        old_ip_txt = old_ip_txt + old_ip_list[i]["host_ip"] + ',';
                    }
                    if (v !== old_ip_txt){modifygroup["group_host"]=v}
                }else{
                    if (v !== modifydata[list_json[k]]){modifygroup[list_json[k]] = v}
                }
                modifygroup["group_id"] = modifydata["group_id"];
            });
            console.log(modifygroup);
            $.ajax({
                url: '/yaml-mod-group/',
                dataType: 'json',
                type: 'POST',
                data: {"data": JSON.stringify(modifygroup)},
                success: function (statusdata) {
                    buttom_status = 1;
                    group_list = statusdata["group_list"];
                    var group_status = statusdata["status"];
                    if (group_status === 0){
                        grouptable.reload({
                            data: group_list
                        });
                        $('#resetgroup').trigger("click");
                        layer.msg('修改成功！')
                    }else{
                        layer.msg("程序异常或数据有误！")
                    }
                }
            })
        }

    });

    $('.demoTable .layui-btn').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
});